# -*- coding: utf-8 -*-
import json

from odoo import http
from odoo.addons.weixin.api.session_manager import session_obj
import logging

_logger = logging.getLogger(__name__)

class WliotMainController(http.Controller):

    @http.route('/wliot/partner/queryAddr', auth='public')
    def queryAddr(self, **kw):
        ''' 查询省市区 '''
        try:
            type = kw.get("type")
            name = kw.get("name")
            code = kw.get("code")

            if type == "province":
                provinces = http.request.env['mxbase.province'].sudo().search([], order='id desc')
                data = []
                for province in provinces:
                    p = {
                        'name': province.name,
                        'code': province.code
                    }
                    data.append(p)
                return json.dumps({
                    'success': True,
                    'message': u'查询成功',
                    'data': data
                })
            elif type == "city":
                province = http.request.env['mxbase.province'].sudo().search([
                    ('name', '=', name),
                    ('code', '=', code)
                ])
                citys = http.request.env['mxbase.city'].sudo().search([
                    ('province_id', '=', province.id)
                ], order='id desc')
                data = []
                for city in citys:
                    d = {
                        'name': city.name,
                        'code': city.code
                    }
                    data.append(d)
                return json.dumps({
                    'success': True,
                    'message': u'查询成功',
                    'data': data
                })
            elif type == "county":
                city = http.request.env['mxbase.city'].sudo().search([
                    ('name', '=', name),
                    ('code', '=', code)
                ])
                countys = http.request.env['mxbase.county'].sudo().search([
                    ('city_id', '=', city.id)
                ], order='id desc')
                data = []
                for county in countys:
                    c = {
                        'name': county.name,
                        'code': county.code
                    }
                    data.append(c)
                return json.dumps({
                    'success': True,
                    'message': u'查询成功',
                    'data': data
                })
            else:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': u'类型错误！'
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'message': error,
                    'code': 500
                })

    @http.route('/wliot/partner/queryPartners', auth='public')
    def queryPartners(self, **kw):
        ''' 按条件查询客户 '''
        try:
            partner = self.get_partner_by_session_id(kw)

            pageSize = kw.get("pageSize", 10)
            pageSize = int(pageSize)
            pageNum = kw.get("pageNum", 1)
            pageNum = int(pageNum)
            offser_val = (pageNum - 1) * pageSize

            province_code = kw.get("provinceCode")
            city_code = kw.get("cityCode")
            county_code = kw.get("countyCode")
            data = []
            if county_code:
                county = http.request.env['mxbase.county'].sudo().search([
                    ('code', '=', county_code)
                ])
                city = http.request.env['mxbase.city'].sudo().search([
                    ('code', '=', city_code)
                ])
                province = http.request.env['mxbase.province'].sudo().search([
                    ('code', '=', province_code)
                ])
                partners = http.request.env['res.partner'].sudo().search([
                    ('province_id', '=', province.id),
                    ('city_id', '=', city.id),
                    ('county_id', '=', county.id)
                ], offset=offser_val, limit=pageSize, order='name desc')
                for partner in partners:
                    if partner.name == 'My Company' or partner.name == 'Administrator':
                        break
                    data.append(partner.get_message())
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
            elif city_code:
                city = http.request.env['mxbase.city'].sudo().search([
                    ('code', '=', city_code)
                ])
                province = http.request.env['mxbase.province'].sudo().search([
                    ('code', '=', province_code)
                ])
                partners = http.request.env['res.partner'].sudo().search([
                    ('province_id', '=', province.id),
                    ('city_id', '=', city.id),
                ], offset=offser_val, limit=pageSize, order='name desc')
                for partner in partners:
                    if partner.name == 'My Company' or partner.name == 'Administrator':
                        break
                    data.append(partner.get_message())
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
            elif province_code:
                province = http.request.env['mxbase.province'].sudo().search([
                    ('code', '=', province_code)
                ])
                partners = http.request.env['res.partner'].sudo().search([
                    ('province_id', '=', province.id),
                ], offset=offser_val, limit=pageSize, order='name desc')
                for partner in partners:
                    if partner.name == 'My Company' or partner.name == 'Administrator':
                        break
                    data.append(partner.get_message())
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
            else:
                partners = http.request.env['res.partner'].sudo().search([
                    ('parent_id', '=', False)
                ], offset=offser_val, limit=pageSize,
                                                                         order='name desc')
                for partner in partners:
                    if partner.name == 'My Company' or partner.name == 'Administrator':
                        break
                    data.append(partner.get_message())
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'message': error,
                    'code': 500
                })

    @http.route('/wliot/partner/searchPartners', auth='public')
    def searchPartners(self, **kw):
        ''' 搜索客户 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'code': 400,
                    'success': False,
                    'message': u'没有改客户！'
                })
            data = []
            name = kw.get('name')
            if not name:
                partners = http.request.env['res.partner'].sudo().search([], order='name desc')
                for partner1 in partners:
                    if partner1.name == 'My Company' or partner1.name == 'Administrator':
                        break
                    data.append(partner1.get_message())
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
            else:
                partners = http.request.env['res.partner'].sudo().search([
                    ('name', 'ilike', name)
                ])
                for partner2 in partners:
                    if partner2.name == 'My Company' or partner2.name == 'Administrator':
                        break
                    data.append(partner2.get_message())
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'message': error,
                    'code': 500
                })

    def get_partner_by_session_id(self, kw):
        '''检查session是否过期，并根据session_id返回该微信号可以查看的客户'''
        session_id = kw.get('SessionID')
        if not session_id:
            return {
                'success': False,
                'code': 400,
                'msg': u'请传入session_id！',
            }
        open_id = session_obj.pydis.get(session_id)
        if not open_id:
            return {
                'success': False,
                'code': 900,
                'msg': u'sessoin已过期，请重新获取！',
            }
        wechat_recs = http.request.env['weixin.user'].sudo().search([('open_id', '=', open_id)])
        partner = http.request.env['res.partner'].sudo().search([('id', '=', wechat_recs.partner_id.id)])
        return partner

    def check_phone_legal(self, phone):
        '''是否存在该电话的客户，若存在则返回该客户'''
        records = http.request.env['res.partner'].sudo().search([
            # ('partner_type', '=', 'customer'),
            ('phone', '=', phone)
        ])
        if not records:
            return {
                'success': False,
                'msg': u'不存在电话为%s的客户！' % phone,
            }
        else:
            return {
                'success': True,
                'value': records,
            }
